<?php
namespace Bob\LaravelApi;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Bob\LaravelApi\Exceptions\GenerateAccessTokenException;
use Bob\LaravelApi\Models\AccessToken;

class Api
{

    /**
     * User model.
     *
     * @var Model
     */
    public static $user;

    /**
     * AccessToken expired after.
     *
     * @var int
     */
    public static $ttl = 0;

    /**
     * Set ttl.
     *
     * @author yansongda <me@yansongda.cn>
     *        
     * @param int $ttl            
     */
    public static function setTtl($ttl = 7200)
    {
        self::$ttl = $ttl;
    }

    /**
     * Generate access_token.
     *
     * @author yansongda <me@yansongda.cn>
     *        
     * @param App $app            
     *
     * @return string
     * @throws GenerateAccessTokenException
     */
    public static function generateAccessToken($user, $provider = "users")
    {
        if (! $user instanceof Model) {
            throw new GenerateAccessTokenException('[' . get_class($user) . '] Must Be An Instance Of [Illuminate\Database\Eloquent\Model]');
        }
        
        return AccessToken::updateOrCreate([
            'user_id' => $user->id,
            'provider' => $provider,
            'long_term' => self::$ttl > 0 ? 0 : 1
        ], [
            'access_token' => md5(uniqid('access_token', true) . $user->id . $provider),
            'expired_at' => Carbon::now()->addSeconds(self::$ttl)
        ]);
    }
}
